package com.jbp.job;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jbp.model.Room;
import com.jbp.model.RoomUserWheat;
import com.jbp.model.User;
import com.jbp.redis.RedisConfigService;
import com.jbp.service.RoomService;
import com.jbp.service.RoomUserWheatService;
import com.jbp.service.UserService;
import com.jbp.utils.Constant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**踢出僵尸用户*/
@Component
@Configuration
public class QuitRoomJob {

    @Autowired
    private RedisConfigService redisConfigService;

    @Autowired
    private RoomUserWheatService roomUserWheatService;

    @Autowired
    private RoomService roomService;

    @Autowired
    private UserService userService;
    /**
     * 系统清理房间僵尸用户逻辑
     */
    @Scheduled(fixedDelay = 1000*30)
//    @Scheduled(fixedDelay = 1000*60*60*60)
    public void quitRoom(){
        if (redisConfigService.setLock("quitRoom", 25)) {
            List<RoomUserWheat> list = roomUserWheatService.list();
            list.forEach(li -> {
                Object object = redisConfigService.get(Constant.ROOM_PREFIX + li.getUserId());
                if (object == null) {
                    //移除离线用户
                    roomUserWheatService.removeById(li.getId());

                    //将设为离线
                    User user = userService.getById(li.getUserId());
                    user.setIsOnline("offline");
                    userService.updateById(user);
                } else {
                    //将设为在房间
                    User user = userService.getById(li.getUserId());
                    if ("offline".equals(user.getIsOnline())) {
                        user.setIsOnline("online");
                        userService.updateById(user);
                    }
                }
            });

            //根据房间人数刷新人气值
            List<Room> roomList = roomService.list();
            roomList.forEach(room -> {
                List<RoomUserWheat> roomUserWheats = roomUserWheatService.list(new QueryWrapper<RoomUserWheat>().eq("room_id", room.getId()));
                int peopleMood = roomUserWheats.stream()
                        .mapToInt(roomUserWheat -> userService.getPeopleMood(roomUserWheat.getUserId())).sum();
                room.setPeopleMood(peopleMood);
                roomService.updateById(room);
            });
        }
    }
}
